package com.quarkus.filter;

import com.quarkus.bean.FroMage;
import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
import org.jboss.resteasy.reactive.server.spi.ServerMessageBodyWriter;
import org.jboss.resteasy.reactive.server.spi.ServerRequestContext;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

/**
 * @version v1.0
 * @Description: Request 和 Response 的 匹配
 * @Author: TongRui乀
 * @Date: 2021/1/24 3:30 下午
 */
@Provider
public class MessageReaderAndWrite implements MessageBodyReader<FroMage>, MessageBodyWriter<FroMage> {
    @Override
    public boolean isReadable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
        return type == FroMage.class;
    }

    @Override
    public FroMage readFrom(Class<FroMage> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> multivaluedMap, InputStream inputStream) throws IOException, WebApplicationException {

        String message = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);

        if(message.contains("_Formage_")){
            return new FroMage(message.substring(9));
        }
        throw new RuntimeException("param invalid");
    }

    @Override
    public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
        return type == FroMage.class;
    }

    @Override
    public void writeTo(FroMage froMage, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> multivaluedMap, OutputStream outputStream) throws IOException, WebApplicationException {
        outputStream.write(("_Formage_" + froMage.getName()).getBytes());
    }
}
